package com.gen.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import com.gen.tool.PlayerInfo;
import com.ouken.tool.ConnectServer;
import com.ouken.tool.MyApp;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;

public class RefreshGameRoomPlayerService extends Service {

	private final IBinder mBinder = new LocalBinder();
	private MyApp appState;
	private WifiManager wifi;
	private String httpUrl;
	private List params;
	private Boolean isRunning;
	private Thread updateGR;
	private static final String NORE = "NoRefresh";
	private Bundle bundleToBroadcast = new Bundle();
	private Intent intentToBroadcast = new Intent("com.gameRoomPlayerUpdateReceiver");
	private static final String ERR_MES = "Pleaseloginfirst";
	private static final String ERR_KICKED = "Youarenotintheroom";
	
	public class LocalBinder extends Binder{
		public RefreshGameRoomPlayerService getService(){
			return RefreshGameRoomPlayerService.this;
		}
	}
	  
	@Override
	public void onDestroy() {
		System.out.println("RefreshGameRoomPlayerService destroy");
		isRunning = false;
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		appState = ((MyApp)getApplicationContext());
		wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
		
		httpUrl = "http://"+ConnectServer.getServerAdd()+"/gameRoomUpdate";
		
		params = new ArrayList();
		params.add(new BasicNameValuePair("roomName", appState.getRoomName().toString()));
		params.add(new BasicNameValuePair("userEmail", appState.getUserEmail()));
		params.add(new BasicNameValuePair("mac", wifi.getConnectionInfo().getMacAddress()));
		params.add(new BasicNameValuePair("ParamEnd", "ParamEndParamEndParamEnd"));
		
		System.out.println("GR player on bind");
		
		updateGR = new Thread(new Runnable(){

			@Override
			public void run() {
				while(isRunning){
					
					System.out.println("GR player Thread is running");
					if(isRunning){
						
				    	String result = doInbackground();
						if(!result.equals(NORE) ){
							bundleToBroadcast.putString("changes", result);
						    intentToBroadcast.putExtras(bundleToBroadcast);
						    sendBroadcast(intentToBroadcast);
						    }
						}
					try{
						Thread.sleep(3000);
					}catch(Exception e){
						System.out.println(e.toString());
					}
					}
				System.out.println("update GR player stop");
				}
			}
		);
		
		isRunning = true;
		updateGR.start();
		
		return mBinder;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		isRunning = false;
		System.out.println("GR Player ON unbind");
		return super.onUnbind(intent);
	}
	
	public String doInbackground(){
		/**-------parameters' defining----------*/
		char paraForReciever[] = {'0','0','0','0','0'};//change or not 1,1,1,1,2 owner,player1-4
											//1 - already existed person, only change the state
											//2 - new person update all
		String[] contents = new String[29];
		
		String usedContents = new String(); //record the user has been used in contents
    	String usedPlayer = new String(); //record the user didn't existed in contents, but in appState
    	String result = new String();
		
		String userId = "0";
		int userIdInt = 0;
		String gameRoomInfo = new String();
		
		/**-------parameters' defining over----------*/

		//for test
		try{
			gameRoomInfo= ConnectServer.connect(httpUrl, params);
		}catch(Exception e){
			System.out.print(e.toString());
		};
		
    	    	
		//---------no message from server----------//
    	if(gameRoomInfo == null){
		}
    	//---------have message from server----------//
    	else{
    		ArrayList<PlayerInfo> playerInfo = new ArrayList<PlayerInfo>(appState.getPlayerList());
	    	HashMap<String,String> playerEmail = new HashMap<String,String>();
    		
    		gameRoomInfo = gameRoomInfo.replaceAll("(\\ )", "");
	    	contents = gameRoomInfo.split(",");
    	
	    	//________OK Message_________//
	    	if(contents[0].equals("OK")&& contents.length == 30){
	    		//for test
	    		try{
	    		String player[][] = {{contents[3],contents[4],contents[5],contents[6],contents[7]},
									{contents[8],contents[9],contents[10],contents[11],contents[12]},
									{contents[13],contents[14],contents[15],contents[16],contents[17]},
									{contents[18],contents[19],contents[20],contents[21],contents[22]},
									{contents[23],contents[24],contents[25],contents[26],contents[27]}};
	    		
	    		Bitmap playerImg;
			
	    		for(int i = 1;i<5;i++){
	    			if(!player[i][1].equals(" ") && !player[i][1].equals("")){
	    				playerEmail.put(player[i][1], String.valueOf(i));
						}
					}
			
	    		//*********refresh***********//
	    		if(appState.getRefreshGRcounter() != 0){
	    			//if the owner changed, the only can be changed element is state
	    			if(playerInfo.get(0).getState().charAt(0) != player[0][4].charAt(0)){
	    				//player changed to manager
	    				if(player[0][4].charAt(0) == '4'){
	    					paraForReciever[0] = '2';
	    					//for test
	    					System.out.print(player[0][4].charAt(0));
	    					return String.valueOf(paraForReciever);
	    				}
	    				else{
	    					paraForReciever[0] = '1';
	    					appState.setPlayerInfoState(0, player[0][4]);	
	    				}
	    			}
	    			
	    			//________refresh users__________//
	    			for(int i = 1; i < 5; i++){
	    				if(!playerInfo.get(i).getUserEmail().equals(" ") && !playerInfo.get(i).getUserEmail().equals("")){
	    					userId =playerEmail.get(playerInfo.get(i).getUserEmail());
    				
	    					//email is same, so is the same person
	    					if(userId != null){
	    						userIdInt = Integer.parseInt(userId);
	    						usedPlayer = usedPlayer + String.valueOf(i);
	    						usedContents = usedContents + String.valueOf(userId);
	    						//if the person already exist, the only can be changed element is state
	    						if(playerInfo.get(i).getState().charAt(0) != player[userIdInt][4].charAt(0)){
	    							paraForReciever[i] = '1';
	    							appState.setPlayerInfoState(i, player[userIdInt][4]);
	    						}
	    					}
	    				}
	    			}
    			
	    			//do the no info player
	    			//if all players' existed, no this op
	    			if(usedPlayer.length() != 4){
	    				if(!appState.getMem().equals(contents[28] + "/" + contents[29])){
	    					for(int i = 1; i < 5; i++){
		    					if(!usedPlayer.contains(String.valueOf(i))){
		    						for(int j = 1; j< 5; j++){
		    							if(!usedContents.contains(String.valueOf(j))){
		    								if(player[j][1].equals(" ") || player[j][1].equals("")){
		    									appState.setPlayerInfo(i, new PlayerInfo().newPlayer(" ", " "," ", null, player[j][4]," "," "));
		    								}
		    								else{
		    									playerImg = ConnectServer.getBitmap(player[j][3]);
		    									appState.setPlayerInfo(i, new PlayerInfo().newPlayer(player[j][1], player[j][0], player[j][2], playerImg, player[j][4], " ", " "));
		    								}
		    								usedPlayer = usedPlayer + String.valueOf(i);
		    								usedContents = usedContents + String.valueOf(j);
		    								paraForReciever[i] = '2';
		    								break;
		    							}
		    						}
		    					}
		    				}
	    				}
	    			}
	    			appState.setMem(contents[28], contents[29]);
	    		}
	    		
	    		//*********update first time***********//
	    		else{
	    			//appState.setClearPlayerInfo();
	    			appState.setRoomName(contents[2]);
	    			appState.iniPlayerInfo(new PlayerInfo().newPlayer(" "," "," ", null, contents[7]," ", " "));
	    			for(int i=1;i<5;i++){ 
	    				if(player[i][1].equals(" ") || player[i][1].equals("")){
	    					appState.iniPlayerInfo(new PlayerInfo().newPlayer(player[i][1],player[i][0], player[i][2], null, player[i][4], " ", " "));
	    				}
	    				else{
	    					playerImg = ConnectServer.getBitmap(player[i][3]);
	    					appState.iniPlayerInfo(new PlayerInfo().newPlayer(player[i][1],player[i][0], player[i][2], playerImg, player[i][4], " ", " "));
	    				} 
	    			}
	    			appState.setMem(contents[28], contents[29]);
	    			System.out.print("first time update in service overed");
	    			return String.valueOf(paraForReciever);
	    		}
	    		//for test
	    		}catch(Exception e){
	    			System.out.print(e.toString()+ "Message is Ok");
	    		}
	    	}//Message is Ok
	    	
	    	//________SG Message_________//
	    	else if(contents[0].equals("SG")){
	    		String temp = new String();
	    		paraForReciever[0] = '3'; 
	    		if(appState.getUserEmail().equals(contents[1])){
					appState.getPlayerByNum(0).setRole("provider");
					System.out.print("I'm provider");
					}
				else{
					appState.getPlayerByNum(0).setRole("challenger");
					System.out.print("I'm challenger");
					}
	    		
	    		for(int i = 1;i<5;i++){
	    			temp = playerInfo.get(i).getUserEmail();
	    			if(temp.equals(" ") || temp.equals("")){
	    				appState.getPlayerByNum(i).setRole(" ");
	    				System.out.print(" ");
					}
	    			else if(temp.equals(contents[1])){
	    					appState.getPlayerByNum(i).setRole("provider");
	    					System.out.print("I'm provider");
					}
	    			else{
	    					appState.getPlayerByNum(i).setRole("challenger");
	    					System.out.print("I'm challenger");
					}
	    		}
	    		return String.valueOf(paraForReciever);
	    	}//Message SG
	    	
	    	//________ERROR Message_________//
    		else if(contents[0].toString().equals("ERROR")){
    			try{
    				if(contents[1].toString().equals(ERR_MES)){
    					paraForReciever[0] = '4';
    	    			return String.valueOf(paraForReciever);
    				}
    				if(contents[1].toString().equals(ERR_KICKED)){
    					paraForReciever[0] = '5';
    	    			return String.valueOf(paraForReciever);
    				}
    				else{
    	    			System.out.println(contents[1].toString());
    	    		}
    				}catch(Exception e){
    					System.out.println(e.toString());
    				}
    		}
	
    	}//have message from server
    	
    	result = String.valueOf(paraForReciever);
    	if(result.equals("00000")){
    		return NORE;
    	}
    	else{
    		return result;
    	}	
	}

}
